package com.fjh.test;


import com.fjh.config.AppConfig;
import com.fjh.pojo.Book;
import com.fjh.pojo.Borrow;
import com.fjh.service.BookService;
import com.fjh.service.BorrowService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.dao.DataIntegrityViolationException;


public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        BookService bookService = context.getBean(BookService.class);
        BorrowService borrowService = context.getBean(BorrowService.class);

        // 1. 添加图书
        Book book = new Book();
        book.setName("Java");
        book.setAuthor("John");
        book.setPublisher("新华");
        book.setPrice(39.99);
        bookService.addBook(book);

        // 2. 查询图书
        int bookId = 1;
        Book retrievedBook = bookService.getBookById(bookId);
        System.out.println("Retrieved Book: " + retrievedBook);

        // 3. 借阅图书
        Borrow borrow = new Borrow();
        borrow.setBookId(bookId);
        borrow.setUserId(1);
        borrowService.borrowBook(borrow);

        // 4. 归还图书
        int borrowId = 1;
        borrowService.returnBook(borrowId);

        // 5. 更新图书
        int bookIdToUpdate = 1;
        Book updatedBook = bookService.getBookById(bookIdToUpdate);
        if (updatedBook != null) {
            updatedBook.setPrice(49.99);  // 设置新的价格
            bookService.updateBook(updatedBook);
            System.out.println("Book updated: " + updatedBook);
        } else {
            System.out.println("Book with ID " + bookIdToUpdate + " not found.");
        }

//         6. 删除图书
        int bookIdToDelete = 9;
        try {
            boolean isDeleted = bookService.deleteBook(bookIdToDelete);
            if (isDeleted) {
                System.out.println("Book with ID " + bookIdToDelete + " deleted successfully.");
            } else {
                System.out.println("Book with ID " + bookIdToDelete + " not found.");
            }
        } catch (DataIntegrityViolationException e) {
            System.out.println("Cannot delete the book due to existing borrow records.");
        }

        // 关闭Spring容器
        context.close();
    }
}